package ch.dreamweb.readpractice.server;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

import javax.persistence.Query;

import org.apache.log4j.Logger;

import ch.dreamweb.readpractice.client.lesetraining.TrainingService;
import ch.dreamweb.readpractice.domain.Setting;
import ch.dreamweb.readpractice.shared.FieldVerifier;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class TrainingServiceImpl extends RemoteServiceServlet implements
		TrainingService {

	static Logger logger = Logger.getLogger("TrainingServiceImpl.class");

	public Setting getSetting(String login) {
		Query settingsByLogin = Setting.findSettingsByLogin(login);
		Setting s = (Setting) settingsByLogin.getSingleResult();
		logger.debug("Setting found: " + s.toString());
		return s;
	}

	@Override
	public String greetServer(String input) throws IllegalArgumentException {
		// Verify that the input is valid.
		if (!FieldVerifier.isValidName(input)) {
			// If the input is not valid, throw an IllegalArgumentException back
			// to
			// the client.
			throw new IllegalArgumentException(
					"Name must be at least 4 characters long");
		}

		String serverInfo = getServletContext().getServerInfo();
		String userAgent = getThreadLocalRequest().getHeader("User-Agent");
		return "Hello, " + input + "!<br><br>I am running " + serverInfo
				+ ".<br><br>It looks like you are using:<br>" + userAgent;
	}

	@Override
	public ArrayList<String> getMorphemsShuffled() throws RuntimeException {
		ArrayList<String> morphems = getMorphems();

		logger.info("Before shuffling, ArrayList contains : " + morphems);
		/*
		 * To shuffle elements of Java ArrayList use, static void shuffle(List
		 * list) method of Collections class.
		 */
		Collections.shuffle(morphems);
		logger.info("After shuffling, ArrayList contains : " + morphems);

		return morphems;
	}

	private ArrayList<String> getMorphems() {

		ArrayList<String> morphems = new ArrayList<String>();

		try {
			Scanner scanner = new Scanner(new File("words.txt"), "UTF-8");
			try {
				while (scanner.hasNextLine()) {
					morphems.add(scanner.nextLine());
				}
			} finally {
				scanner.close();
			}
		} catch (IOException e) {
			logger.error("Cannot read words file", e);
			throw new RuntimeException("Problem reading morphems text file", e);
		}
		// Jedes Mal Morpheme mischen;
		Collections.shuffle(morphems);
		return morphems;
	}
}
